#!/usr/bin  python
# _*_ coding:utf-8 _*_
"""
----------------------------------
    File Name: families
    Description:
        Author: Dell
        Date: 2020/8/6
-----------------------------------
"""

import datetime
import requests
from rest_framework.views import APIView
from rest_framework.response import Response
from extensions.auth import JwtAuthorizationAuthentication
from Baby import models
from EducationContent.models import Hospital
from Baby.serializers import baby, parent
from Common.logger import app_log
from Common.response import resp
from django.db.models import Max
from extensions import babysense


class FamilyView(APIView):
    # authentication_classes = [JwtAuthorizationAuthentication, ]

    def get(self, request, *args, **kwargs):
        try:
            params = request.query_params
            hospital = params["hospital"]
            group = params["group"]
            status = params["status"]
            if hospital != "ALL":
                if group != "ALL":
                    if status != "ALL":
                        family_data = models.UsersBabies.objects.filter(hospital=hospital, group=group,
                                                                        babies__status=status
                                                                        ).values("family_id", "group", "hospital",
                                                                                 "babies",
                                                                                 "babies__full_name",
                                                                                 "babies__first_name",
                                                                                 "babies__last_name",
                                                                                 "babies__birthday",
                                                                                 "babies__gender", "babies__mrn_last4",
                                                                                 "babies__status", "users__full_name",
                                                                                 "users",
                                                                                 "users__email", "users__relationship",
                                                                                 "users__first_name",
                                                                                 "users__last_name",
                                                                                 "users__study_id_number",
                                                                                 "users__relationship").all()
                    else:
                        family_data = models.UsersBabies.objects.filter(hospital=hospital, group=group
                                                                        ).values("family_id", "group", "hospital",
                                                                                 "babies",
                                                                                 "babies__full_name",
                                                                                 "babies__first_name",
                                                                                 "babies__last_name",
                                                                                 "babies__birthday",
                                                                                 "babies__gender", "babies__mrn_last4",
                                                                                 "babies__status", "users__full_name",
                                                                                 "users",
                                                                                 "users__email", "users__relationship",
                                                                                 "users__first_name",
                                                                                 "users__last_name",
                                                                                 "users__study_id_number",
                                                                                 "users__relationship").all()
                else:
                    if status != "ALL":
                        family_data = models.UsersBabies.objects.filter(hospital=hospital, babies__status=status
                                                                        ).values("family_id", "group", "hospital",
                                                                                 "babies",
                                                                                 "babies__full_name",
                                                                                 "babies__first_name",
                                                                                 "babies__last_name",
                                                                                 "babies__birthday",
                                                                                 "babies__gender", "babies__mrn_last4",
                                                                                 "babies__status", "users__full_name",
                                                                                 "users",
                                                                                 "users__email", "users__relationship",
                                                                                 "users__first_name",
                                                                                 "users__last_name",
                                                                                 "users__study_id_number",
                                                                                 "users__relationship").all()
                    else:
                        family_data = models.UsersBabies.objects.filter(hospital=hospital
                                                                        ).values("family_id", "group", "hospital",
                                                                                 "babies",
                                                                                 "babies__full_name",
                                                                                 "babies__first_name",
                                                                                 "babies__last_name",
                                                                                 "babies__birthday",
                                                                                 "babies__gender", "babies__mrn_last4",
                                                                                 "babies__status", "users__full_name",
                                                                                 "users",
                                                                                 "users__email", "users__relationship",
                                                                                 "users__first_name",
                                                                                 "users__last_name",
                                                                                 "users__study_id_number",
                                                                                 "users__relationship").all()
            else:
                if group != "ALL":
                    if status != "ALL":
                        family_data = models.UsersBabies.objects.filter(group=group,
                                                                        babies__status=status
                                                                        ).values("family_id", "group", "hospital",
                                                                                 "babies",
                                                                                 "babies__full_name",
                                                                                 "babies__first_name",
                                                                                 "babies__last_name",
                                                                                 "babies__birthday",
                                                                                 "babies__gender", "babies__mrn_last4",
                                                                                 "babies__status", "users__full_name",
                                                                                 "users",
                                                                                 "users__email", "users__relationship",
                                                                                 "users__first_name",
                                                                                 "users__last_name",
                                                                                 "users__study_id_number",
                                                                                 "users__relationship").all()
                    else:
                        family_data = models.UsersBabies.objects.filter(group=group
                                                                        ).values("family_id", "group", "hospital",
                                                                                 "babies",
                                                                                 "babies__full_name",
                                                                                 "babies__first_name",
                                                                                 "babies__last_name",
                                                                                 "babies__birthday",
                                                                                 "babies__gender", "babies__mrn_last4",
                                                                                 "babies__status", "users__full_name",
                                                                                 "users",
                                                                                 "users__email", "users__relationship",
                                                                                 "users__first_name",
                                                                                 "users__last_name",
                                                                                 "users__study_id_number",
                                                                                 "users__relationship").all()
                else:
                    if status != "ALL":
                        family_data = models.UsersBabies.objects.filter(babies__status=status
                                                                        ).values("family_id", "group", "hospital",
                                                                                 "babies",
                                                                                 "babies__full_name",
                                                                                 "babies__first_name",
                                                                                 "babies__last_name",
                                                                                 "babies__birthday",
                                                                                 "babies__gender", "babies__mrn_last4",
                                                                                 "babies__status", "users__full_name",
                                                                                 "users",
                                                                                 "users__email", "users__relationship",
                                                                                 "users__first_name",
                                                                                 "users__last_name",
                                                                                 "users__study_id_number",
                                                                                 "users__relationship").all()
                    else:
                        family_data = models.UsersBabies.objects.values("family_id", "group", "hospital",
                                                                        "babies",
                                                                        "babies__full_name", "babies__first_name",
                                                                        "babies__last_name", "babies__birthday",
                                                                        "babies__gender", "babies__mrn_last4",
                                                                        "babies__status", "users__full_name",
                                                                        "users",
                                                                        "users__email", "users__relationship",
                                                                        "users__first_name", "users__last_name",
                                                                        "users__study_id_number",
                                                                        "users__relationship").all()
            first_handle_data = {}

            for single_family_data in family_data:
                family_data_list = []
                if single_family_data["family_id"] not in first_handle_data:
                    family_id = single_family_data["family_id"]
                    first_handle_data[family_id] = family_data_list
                    first_handle_data[family_id].append(single_family_data)
                else:
                    family_id = single_family_data["family_id"]
                    first_handle_data[family_id].append(single_family_data)
            second_handle_data = {}
            for k, v in first_handle_data.items():
                single_family_dict = {}
                second_handle_data[k] = single_family_dict
                baby_dic = {}
                baby_list = []
                for i in v:
                    if i["babies"] not in baby_dic:
                        single_baby_dic = {}
                        baby_dic[i["babies"]] = single_baby_dic
                        single_baby_dic["full_name"] = i["babies__full_name"]
                        single_baby_dic["first_name"] = i["babies__first_name"]
                        single_baby_dic["last_name"] = i["babies__last_name"]
                        single_baby_dic["gender"] = i["babies__gender"]
                        single_baby_dic["mrn"] = "XXXXX{}".format(i["babies__mrn_last4"])
                        single_baby_dic["birthday"] = i["babies__birthday"]
                        single_baby_dic["id"] = i["babies"]
                        baby_list.append(single_baby_dic)
                single_family_dict["all_baby_list"] = baby_list
                family_dict = {}
                family_list = []
                for i in v:
                    if i["users"] not in family_dict:
                        relationship_dict = {}
                        family_dict[i["users"]] = relationship_dict
                        single_family_dict["group"] = i.pop("group")
                        single_family_dict["status"] = i.pop("babies__status")
                        single_family_dict["family_id"] = i.pop("family_id")
                        single_family_dict["hospital"] = i.pop("hospital")
                        relationship_dict["id"] = i["users"]
                        relationship_dict["full_name"] = i["users__full_name"]
                        relationship_dict["first_name"] = i["users__first_name"]
                        relationship_dict["last_name"] = i["users__last_name"]
                        relationship_dict["email"] = i["users__email"]
                        relationship_dict["study_id_number"] = i["users__study_id_number"]
                        relationship_dict["relationship"] = i["users__relationship"]
                        family_list.append(relationship_dict)
                single_family_dict["all_family_list"] = family_list
            return Response({
                'error_code': 0,
                'message': "Success",
                'data': second_handle_data
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)

    def post(self, request, *args, **kwargs):
        try:
            data = request.data
            hospital = data["hospital"]
            group = data["group"]
            parent_data = data["parent"]
            baby_data = data["baby"]
            parent_id_list = []
            for p in parent_data:
                email = p["email"]
                parent_db_data = models.Users.objects.filter(email=email)
                if parent_db_data.exists():
                    return resp(2001, {})
            for b in baby_data:
                baby_full_name = "{} {}".format(b["first_name"], b["last_name"])
                baby_db_data = models.Babies.objects.filter(full_name=baby_full_name)
                if baby_db_data.exists():
                    return resp(2002, {})
            for single_parent_data in parent_data:
                parent_ser = parent.ParentModelSerializer(data=single_parent_data)
                parent_ser.is_valid(raise_exception=True)
                parent_obj = parent_ser.save()
                parent_id_list.append(parent_obj.id)
            one_parent_obj = models.Users.objects.get(id=parent_id_list[0])
            one_parent_obj.spouse_id = parent_id_list[1]
            one_parent_obj.save()
            another_parent_obj = models.Users.objects.get(id=parent_id_list[1])
            another_parent_obj.spouse_id = parent_id_list[0]
            another_parent_obj.save()
            baby_id_list = []
            for single_baby_data in baby_data:
                baby_ser = baby.BabyModelSerializer(data=single_baby_data)
                baby_ser.is_valid(raise_exception=True)
                baby_obj = baby_ser.save()
                baby_id_list.append(baby_obj.id)
                """
                requests.post() ----> babysense interface
                more hospital to do
                """
                # hospital_url = Hospital.objects.filter(hospital_name=hospital).values("hospital_url").first()
                # hospital_url = hospital_url["hospital_url"]
                hospital_url = "https://babysense-staging.fsm.northwestern.edu"
                url = hospital_url + babysense.BabySense_Url["create_baby"]
                app_log.info("api url --->{}".format(url))
                single_baby_data["mrn"] = single_baby_data.pop("mrn_hash")
                single_baby_data.pop("expected_birthday")
                single_baby_data.pop("hospital")
                single_baby_data.pop("group")
                app_log.info("================= Babysense api create baby params===============")
                app_log.info(single_baby_data)
                app_log.info("================= Babysense api create baby params===============")
                response = requests.post(url, json=single_baby_data, headers={
                    'content-type': 'application/json'
                })
                app_log.info("================= Babysense api create baby===============")
                app_log.info("create baby response --> {}".format(response))
                app_log.info("================= Babysense api create baby===============")
                if response.status_code == "200":
                    babysense_data = response.json()
                    if "validated" in babysense_data:
                        baby_obj.validated = babysense_data["validated"]
                    else:
                        baby_obj.validated = False
                    baby_obj.babysense_id = babysense_data["babysense_id"]
                    baby_obj.expected_birthday = babysense_data["expected_birthday"]
                    baby_obj.save()
                else:
                    baby_obj.validated = False
                    baby_obj.save()
                    app_log.info("babysense create baby api error:{}".format(resp(1007, {})))
            family_id_max = models.UsersBabies.objects.all().aggregate(Max('family_id'))['family_id__max']
            if family_id_max is None:
                family_id_max = 0
            family_id = family_id_max + 1
            for single_parent_id in parent_id_list:
                for single_baby_id in baby_id_list:
                    models.UsersBabies.objects.create(babies_id=single_baby_id, users_id=single_parent_id,
                                                      family_id=family_id, group=group, hospital=hospital)
            return Response({
                'error_code': 0,
                'message': "Success"
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)

    def put(self, request, *args, **kwargs):
        try:
            data = request.data
            hospital = data["hospital"]
            group = data["group"]
            parent_data = data["parent"]
            baby_data = data["baby"]
            time_now = datetime.datetime.now()
            for p in parent_data:
                email = p["email"]
                parent_id = p["id"]
                parent_db_data = models.Users.objects.filter(email=email).exclude(id=parent_id)
                if parent_db_data.exists():
                    return resp(2001, {})
            parent_id_list = []
            for single_parent_data in parent_data:
                single_parent_data_id = single_parent_data.pop("id")
                parent_id_list.append(single_parent_data_id)
                single_parent_data["full_name"] = "{} {}".format(single_parent_data["first_name"],
                                                                 single_parent_data["last_name"])
                single_parent_data["updated_at"] = time_now
                models.Users.objects.filter(id=single_parent_data_id).update(**single_parent_data)
            for single_baby_data in baby_data:
                single_baby_data_id = single_baby_data.pop("id")
                single_baby_data["updated_at"] = time_now
                models.Babies.objects.filter(id=single_baby_data_id).update(**single_baby_data)
                """
                requests.put() ----> babysense.check_babay
                more hospital to do
                """
                # hospital_url = Hospital.objects.filter(hospital_name=hospital).values("hospital_url").first()
                # hospital_url = hospital_url["hospital_url"]
                hospital_url = "https://babysense-staging.fsm.northwestern.edu"
                url = hospital_url + babysense.BabySense_Url["check_baby"] + str(single_baby_data_id)
                app_log.info("api url --->{}".format(url))
                babysense_data = models.Babies.objects.filter(id=single_baby_data_id).values("babysense_id").first()
                if babysense_data:
                    babysense_token = babysense_data["babysense_id"]
                    gender = baby_data["gender"]
                else:
                    babysense_token = ""
                    gender = ""
                put_data = {}
                put_data["babysense_id"] = babysense_token
                put_data["gender"] = gender
                app_log.info("================= Babysense api update baby params===============")
                app_log.info(put_data)
                app_log.info("================= Babysense api update baby params===============")
                response = requests.put(url, json=put_data, headers={
                    'content-type': 'application/json'
                })
                app_log.info("================= Babysense api update baby===============")
                app_log.info("update baby response --> {}".format(response))
                app_log.info("================= Babysense api update baby===============")
                if response.status_code == "200":
                    pass
                else:
                    app_log.info("babysense update baby api error:{}".format(resp(1007, {})))
            models.UsersBabies.objects.filter(users_id__in=parent_id_list).update(hospital=hospital, group=group,
                                                                                  updated_at=time_now)
            return Response({
                'error_code': 0,
                'message': "Success"
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)
